package com.faxsun.admin.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.EmailValidator;
import org.broadleafcommerce.common.email.service.EmailService;
import org.broadleafcommerce.common.email.service.exception.EmailException;
import org.broadleafcommerce.common.email.service.info.EmailInfo;
import org.broadleafcommerce.openadmin.web.controller.AdminAbstractController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/" + BulkEmailAdminController.SECTION_KEY)
public class BulkEmailAdminController extends AdminAbstractController {

	private static final Log LOG = LogFactory.getLog(BulkEmailAdminController.class);

	protected static final String SECTION_KEY = "bulkemail";
	protected static String defaultBulkEmailView = "modules/defaultContainer";

	@Resource(name = "blEmailService")
	protected EmailService emailService;

	@Resource(name = "fsBulkEmailInfo")
	protected EmailInfo bulkEmailInfo;

	public EmailInfo getBulkEmailInfo() {
		return bulkEmailInfo;
	}

	public void setBulkEmailInfo(EmailInfo bulkEmailInfo) {
		this.bulkEmailInfo = bulkEmailInfo;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String init(Model model) {
		model.addAttribute("viewType", "bulkemail");
		setModelAttributes(model, SECTION_KEY);

		return defaultBulkEmailView;
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String uploadEmailCSVFile(@RequestParam("uploadEmailCSV") MultipartFile file, Model model) {

		if (!file.isEmpty()) {
			// List<String> emailAddressList = new ArrayList<String>();
			String line = null;
			StringBuffer emailAddressesBuffer = new StringBuffer();
			try {
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
						file.getInputStream()));

				try {
					bufferedReader.readLine();
					while ((line = bufferedReader.readLine()) != null) {
						String[] itemArray = line.split(",");
						String item = itemArray[itemArray.length - 1];
						// emailAddressList.add(item);
						emailAddressesBuffer.append(item + ";");
					}

				} finally {
					bufferedReader.close();
				}

			} catch (IOException e) {
				LOG.error("Error while reading file: " + file.getName());
				e.printStackTrace();
			}

			model.addAttribute("viewType", "bulkemail");
			model.addAttribute("emailAddresses", emailAddressesBuffer);
			setModelAttributes(model, SECTION_KEY);
		}

		return defaultBulkEmailView;
	}

	@RequestMapping(value = "/send", method = RequestMethod.POST)
	public String sendBulkEmail(@RequestParam("emailAddrToSend") String emailAddresses, Model model) {

		String[] emailAddressArray = emailAddresses.split(";");
		int errorCount = 0;
		for (String emailAddress : emailAddressArray) {
			emailAddress = emailAddress.replaceAll(" ", "");
			emailAddress = emailAddress.replaceAll("\"", "");

			if (!EmailValidator.getInstance().isValid(emailAddress)) {
				LOG.warn(emailAddress + " is not a valid email address");
				errorCount++;
				continue;
			}

			Map<String, Object> props = new HashMap<String, Object>();
			try {
				emailService.sendTemplateEmail(emailAddress, getBulkEmailInfo(), props);
			} catch (EmailException e) {
				LOG.warn("Got exception while sending out email to: " + emailAddress);
				errorCount++;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		model.addAttribute("viewType", "bulkemail");
		model.addAttribute("message", "发送成功! 共" + errorCount + "个地址无法投递。");
		setModelAttributes(model, SECTION_KEY);

		return defaultBulkEmailView;
	}

}
